//
//  LoginViewController.m
//  QuickCure1
//
//  Created by maoge on 16/10/30.
//  Copyright © 2016年 maoge. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginTextField.h"
#import "Users.h"
#import "RegisterViewController.h"
#import "ProgressManager.h"
#import "Users.h"
#import "SettingChangeController.h"


#import <SMS_SDK/SMSSDK.h>

@interface LoginViewController ()

@property(nonatomic,weak)UITextField *userName_tf;
@property(nonatomic,weak)UITextField *password_tf;

//判断短信登录还是密码登录
@property(nonatomic,assign)BOOL isByMessage;

@property(nonatomic,weak)UIButton *message_btn;

@property(nonatomic,weak)UIButton *getCodeBtn;

@property(nonatomic,assign)BOOL isGetCodeClick;


//模拟正确的用户名和密码
@property(nonatomic,copy)NSString *userName;
@property(nonatomic,copy)NSString *passWord;


@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    //假设从服务器获取的正确的账号密码
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _userName = @"111";
        _passWord = @"111";
        
        //把当前密码存在沙盒中,假设沙盒就是服务器
        [MLDefaults setValue:_userName forKey:kNowUsernameKey];
        [MLDefaults setValue:_passWord forKey:kNowPasswordKey];
        //同步
        [MLDefaults synchronize];
    });

    
    [self setupUI];
    //接收键盘弹出的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveKeyboardNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];

}

- (void)receiveKeyboardNotification:(NSNotification*)notification
{
    CGRect endFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat endY = endFrame.origin.y;
    
    CGFloat transformY = [UIScreen mainScreen].bounds.size.height - endY;
    //transformY过大,把输入框顶了出去
    if (transformY) {
        self.view.transform = CGAffineTransformMakeTranslation(0,-100);
    }else{
        self.view.transform = CGAffineTransformMakeTranslation(0,0);
    }

}


#pragma mark -
#pragma mark - 搭建登录界面
- (void)setupUI
{
    //标题
    self.title = @"用户登录";
    //两张logo图片
    UIImageView *imageViewUp = [[UIImageView alloc]init];
    imageViewUp.image = [UIImage imageNamed:@"product_img_logo_nor.png"];
    [self.view addSubview:imageViewUp];
    
    UIImageView *imageViewDown = [[UIImageView alloc]init];
    imageViewDown.image = [UIImage imageNamed:@"product_text_logo_nor.png"];
    [self.view addSubview:imageViewDown];
    
    //两个输入框
    LoginTextField *userName_tf = [[LoginTextField alloc]initWithPlaceholder:@"请输入账号"];
    LoginTextField *password_tf = [[LoginTextField alloc]initWithPlaceholder:@"请输入密码"];
    
    _userName_tf = userName_tf;
    _password_tf = password_tf;
    
    //数字键盘
    userName_tf.keyboardType = UIKeyboardTypeNumberPad;
    //密码
    password_tf.secureTextEntry = YES;

    
    [self.view addSubview:userName_tf];
    [self.view addSubview:password_tf];
    
    //获取短信验证码按钮
    UIButton *getCodeBtn = [[UIButton alloc]init];
    _getCodeBtn = getCodeBtn;
    [getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    getCodeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [getCodeBtn setTitleColor:kThemeColor forState:UIControlStateNormal];
    [getCodeBtn setBackgroundColor:[UIColor colorWithWhite:0.888 alpha:1]];
    
    [self.view addSubview:getCodeBtn];
    //隐藏短信验证码按钮
    getCodeBtn.hidden = YES;
    
    //添加获取短信验证码监听
    [getCodeBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    
    
    //通过短信验证码登录
    UIButton *message_btn = [UIButton buttonWithType:UIButtonTypeSystem];
    _message_btn = message_btn;
    [message_btn setTitle:@"通过短信验证码登录" forState:UIControlStateNormal];
    //设置字体
    message_btn.titleLabel.font = [UIFont systemFontOfSize:18];
    [self.view addSubview:message_btn];

    
    
    //登录按钮
    UIButton *login_btn = [[UIButton alloc]init];
    [login_btn setTitle:@"登录" forState:UIControlStateNormal];
    [login_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [login_btn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    login_btn.backgroundColor = kThemeColor;
    
    [self.view addSubview:login_btn];
    
    //注册新账号与忘记密码按钮
    UIButton *regist_btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [regist_btn setTitle:@"注册新账号" forState:UIControlStateNormal];
    
    UIButton *forget_btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [forget_btn setTitle:@"忘记密码" forState:UIControlStateNormal];
    //设置字体
    regist_btn.titleLabel.font = [UIFont systemFontOfSize:20];
    forget_btn.titleLabel.font = [UIFont systemFontOfSize:20];
    
    [self.view addSubview:regist_btn];
    [self.view addSubview:forget_btn];
    
    //中间一条线图片
    UIImageView *line_iv = [[UIImageView alloc]init];
    line_iv.image = [UIImage imageNamed:@"illness_img_line.png"];
    
    [self.view addSubview:line_iv];
    
    //设置约束
    //上面图片约束
    [imageViewUp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(67));
        make.height.equalTo(@(88));
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(100);
    }];
    //下面图片约束
    [imageViewDown mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(83));
        make.height.equalTo(@(49));
        make.centerX.equalTo(self.view);
        make.top.equalTo(imageViewUp.mas_bottom);
    }];
    
    //输入框约束
    [userName_tf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(50);
        make.trailing.equalTo(self.view).offset(-50);
        make.top.equalTo(imageViewDown).offset(70);
        
    }];
    [password_tf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(50);
        make.trailing.equalTo(self.view).offset(-50);
        //make.trailing.equalTo(self.view).offset(-160);

        make.top.equalTo(userName_tf).offset(50);
        
    }];
    
    //获取短信验证码按钮的约束
    [getCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(password_tf.mas_trailing).offset(30);
        make.top.equalTo(userName_tf).offset(50);
    }];
    
    
    //通过短信验证码登录约束
    [message_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(password_tf.mas_bottom).offset(20);
      //  make.width.equalTo(@(200));
    }];
    
    
    //登录按钮
    [login_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(50);
        make.trailing.equalTo(self.view).offset(-50);
        make.top.equalTo(message_btn.mas_bottom).offset(30);
    }];
    
    //中间一条线图片约束
    [line_iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(login_btn.mas_bottom).offset(50);
        make.height.equalTo(@(52));
        make.width.equalTo(@(1));
    }];
    
    //注册新账号与忘记密码按钮约束
    [regist_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(line_iv);
        make.trailing.equalTo(line_iv.mas_leading).offset(-20);
    }];
    
    [forget_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(line_iv);
        make.leading.equalTo(line_iv.mas_trailing).offset(20);
    }];
    
    //添加按钮的事件
    [message_btn addTarget:self action:@selector(loginWithmessage) forControlEvents:UIControlEventTouchUpInside];
    [login_btn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [regist_btn addTarget:self action:@selector(regist) forControlEvents:UIControlEventTouchUpInside];
    [forget_btn addTarget:self action:@selector(forgetPassword) forControlEvents:UIControlEventTouchUpInside];
    
    
}

#pragma mark -
#pragma mark - 通过短信验证码登录
- (void)loginWithmessage
{
    _isByMessage = !_isByMessage;
    if (_isByMessage) {
        [_message_btn setTitle:@"通过注册密码登录" forState:UIControlStateNormal];
        

        
        [self.password_tf mas_updateConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self.view).offset(-160);
        }];
        //显示获取验证码按钮
        self.getCodeBtn.hidden = !_isByMessage;
        
        self.userName_tf.placeholder = @"请输入手机号";
        self.password_tf.placeholder = @"请输入验证码";
        self.password_tf.keyboardType = UIKeyboardTypeNumberPad;
        
        
    }else{
        [_message_btn setTitle:@"通过短信验证码登录" forState:UIControlStateNormal];
        [self.password_tf mas_updateConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self.view).offset(-50);
        }];
        self.getCodeBtn.hidden = !_isByMessage;
        
        self.userName_tf.placeholder = @"请输入账号";
        self.password_tf.placeholder = @"请输入密码";
        self.password_tf.keyboardType = UIKeyboardTypeDefault;
    }
}




#pragma mark -
#pragma mark - 获取短信验证码
- (void)getCode
{
    
    //发送验证码短信
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.userName_tf.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
        //发送成功
        if (!error) {
            //倒计时
            [self runTime];
        }
        else{
            //发送错误
            NSLog(@"输入错误");
        }
    }];
    
}

//获取验证码倒计时
- (void)runTime
{
    __block int timeout= 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.getCodeBtn setTitle:@" 获取验证码 " forState:UIControlStateNormal];
                self.getCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [self.getCodeBtn setTitle:[NSString stringWithFormat:@"%@秒后发送",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                self.getCodeBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}



#pragma mark -
#pragma mark - 直接登录
- (void)login
{
    //需要判断密码登录还是验证码登录
    NSString *userName = self.userName_tf.text;
    NSString *password = self.password_tf.text;
    
    //验证码登录
    if (_isByMessage) {
        [SMSSDK commitVerificationCode:password phoneNumber:userName zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error) {
            //验证成功
            if (!error) {
                [self loginSuccess];
            }else{
                //验证失败
                [ProgressManager alertErrorStatus:@"验证码错误"];
            }
        }];
    }else{
        //注册密码登录
        if ([userName isEqualToString:[MLDefaults valueForKey:kNowUsernameKey]] && [password isEqualToString:[MLDefaults valueForKey:kNowPasswordKey]]) {
         //成功
            [self loginSuccess];
        }else{
            //失败
            [ProgressManager alertErrorStatus:@"密码错误"];
          
        }
    }
}
#pragma mark -
#pragma mark - 登录成功
- (void)loginSuccess
{
    [[NetWorkManager sharedManager] loginUserWihtAccount:self.userName_tf.text password:self.password_tf.text successBlock:^(Users *dto) {
      //  NSLog(@"------------------------%@",dto);
        
        
        //显示左边视图
        JASidePanelController *sideVc = (JASidePanelController*)[UIApplication sharedApplication].keyWindow.rootViewController;
        
        [sideVc showLeftPanelAnimated:YES];
        
        
        
        //保存登陆成功到偏好设置
        [MLDefaults setBool:YES forKey:kIsUserLoginKey];
        //同步
        [MLDefaults synchronize];
        
        //左栏控制器显示登录后界面
        if (_loginBLock) {
            _loginBLock(dto);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } errorBlock:^(NSString *error) {
        NSLog(@"%@",error);
    }];
}




#pragma mark -
#pragma mark - 注册新账号
- (void)regist
{
    //挑战到注册页面
    RegisterViewController *registerVc = [[RegisterViewController alloc]init];
    
    [self.navigationController pushViewController:registerVc animated:YES];
}


#pragma mark -
#pragma mark - 忘记密码
- (void)forgetPassword
{
    
    SettingChangeController *changeVC =  [[UIStoryboard storyboardWithName:@"SettingChange" bundle:nil] instantiateViewControllerWithIdentifier:@"change"];
    changeVC.isForget = YES;
    
    [self jumpToOtherViewController:changeVC];
    
    
}


//点击空白处隐藏键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_userName_tf resignFirstResponder];
    [_password_tf resignFirstResponder];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
